package cmd

import (
	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/logger"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/config"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/clickhouse"
	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/executor"
	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/migrator"

	"github.com/riete/errors"
	"github.com/spf13/cobra"
)

var (
	source  *clickhouse.Clickhouse
	sqlFile string
)

// genCmd represents the gen command
var genCmd = &cobra.Command{
	Use:   "gen",
	Short: "generate config or sql",
	Long:  "",
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		var err errors.Error
		source, err = clickhouse.New(config.Config.Source)
		if err != nil {
			logger.Fatal(err.Trace("连接源数据库失败").Stack())
		}
	},
}

// configCmd represents the config command
var configCmd = &cobra.Command{
	Use:   "config",
	Short: "generate config",
	Long:  "",
	Run: func(cmd *cobra.Command, args []string) {
		if err := migrator.GenerateConfig(source, configFile); err != nil {
			logger.Fatal(err.Stack())
		}
		logger.Info("配置文件填充成功")
	},
}

// sqlCmd represents the sql command
var sqlCmd = &cobra.Command{
	Use:   "sql",
	Short: "generate sql",
	Long:  "",
	Run: func(cmd *cobra.Command, args []string) {
		e := executor.New()
		reverse, _ := cmd.Flags().GetBool("reverse")
		e.WriteSqlToFile(source, sqlFile, reverse)
	},
}

func init() {
	genCmd.AddCommand(configCmd, sqlCmd)
	sqlCmd.Flags().StringVarP(&sqlFile, "sql-file", "s", "migration.sql", "/path/to/sql-file")
	sqlCmd.Flags().BoolP("reverse", "r", false, "generate SQL in reverse order")

}
